package netty.demo.nio.selector.dealMessage;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

import static netty.demo.nio.byteBuffer.ByteBufferUtil.debugAll;

/**
 * @author Zed
 * @description Selector--处理Accept事件
 * @date 2022/10/23 10:13
 */
@Slf4j
public class Server {
    private static void split(ByteBuffer source) {
        source.flip();
        for (int i = 0; i < source.limit(); i++) {
            //找到完整消息
            if (source.get(i) == '\n') {
                int length = i + 1 - source.position();
                //把这条完整消息存入新的byteBuffer中
                ByteBuffer target = ByteBuffer.allocate(length);
                //从source读，向target写
                for (int j = 0; j < length; j++) {
                    target.put(source.get());
                }
                debugAll(target);
            }
        }
        source.compact();
    }

    @SneakyThrows
    public static void main(String[] args) {
        //1.创建selector 管理多个channel
        Selector selector = Selector.open();
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        //2.建立selector和channel的联系(注册)
        //sscKey就是将来事件发生后,通过它可以知道事件和哪个channel的事件
        SelectionKey sscKey = ssc.register(selector, 0, null);
        //sscKey只关注accept事件
        sscKey.interestOps(SelectionKey.OP_ACCEPT);
        System.out.println("sscKey:" + sscKey);
        ssc.bind(new InetSocketAddress(8080));
        while (true) {
            //3.select方法,没有事件发生，线程阻塞；有事件发生，线程才会恢复运行
            //select在事件未处理时 不会阻塞，事件发生后要么取消，要么处理，不能置之不理
            selector.select();
            //4.处理事件 selectionKeys内部包含了所有发生的事件
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                iterator.remove();
                System.out.println("key:" + key);
                //5.区分事件类型
                if (key.isAcceptable()) {  //如果是Accept
                    ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                    SocketChannel sc = channel.accept();
                    sc.configureBlocking(false);
                    ByteBuffer buffer = ByteBuffer.allocate(16);
                    //将一个byteBuffer作为附件关联到selectionKey上
                    SelectionKey scKey = sc.register(selector, 0, buffer);
                    scKey.interestOps(SelectionKey.OP_READ);
                    System.out.println(sc);
                    System.out.println("scKey:" + scKey);
                } else if (key.isReadable()) {  //如果是Read,拿触发事件的channel
                    try {
                        SocketChannel channel = (SocketChannel) key.channel();
                        //获取selectionKey上关联的附件
                        ByteBuffer buffer = (ByteBuffer) key.attachment();
                        int readCount = channel.read(buffer);//如果是正常断开,read方法的返回值是-1
                        if (readCount == -1) {
                            key.cancel();
                        } else {
                            split(buffer);
                            //当position值达到limit时,缓冲区就无空间可写了
                            if (buffer.position() == buffer.limit()) {
                                ByteBuffer newByteBuffer = ByteBuffer.allocate(buffer.capacity() * 2);
                                buffer.flip();
                                newByteBuffer.put(buffer);
                                //将新的byteBuffer关联到key
                                key.attach(newByteBuffer);
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        key.cancel();
                    }
                }
            }
        }
    }
}
